use crate::models::checkout::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/checkout", post(create))
        .route("/checkout/:id", get(get_by_id))
        .route("/checkout/:id/delete", post(delete))
        .route("/checkout/by-customer/:customer_id", get(get_by_customer))
        .route("/checkout/by-guest/:guest_id", get(get_by_guest))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let checkout = checkout::Model::create(&state.db, &params).await?;
    format::json(checkout)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let checkout = checkout::Model::find_by_id(&state.db, &id).await?;
    format::json(checkout)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let checkout = checkout::Model::find_by_id(&state.db, &id).await?;
    checkout.delete(&state.db).await?;
    format::json(())
}

async fn get_by_customer(
    State(state): State<AppContext>,
    axum::extract::Path(customer_id): axum::extract::Path<String>,
) -> Result<Response> {
    let checkouts = checkout::Model::find_by_customer_id(&state.db, &customer_id).await?;
    format::json(checkouts)
}

async fn get_by_guest(
    State(state): State<AppContext>,
    axum::extract::Path(guest_id): axum::extract::Path<String>,
) -> Result<Response> {
    let checkouts = checkout::Model::find_by_guest_id(&state.db, &guest_id).await?;
    format::json(checkouts)
}
